import React from 'react';
import Img from './img'
import UpInput from './upInput'
import './index.css'

export default class UpImage extends React.Component{

    constructor() {
        super();
        this.state = {
            imgList:[],
            imgIdx:-1
        }
    }
    handleUpImg = (imgIdx)=>{
        //记录更新那张图片
        if(imgIdx !== undefined){
            this.setState({
                imgIdx
            })
        }
        this.iptRef.click()
    }
    //接受子组件的 ref
    changeIptRef = (ref)=>{
        this.iptRef = ref;
    }
    // input 的 onchange事件
    onChangeUpImage = (e)=>{
        const read = new FileReader();
        read.readAsDataURL(e.target.files[0])
        read.onload = (e)=>{
            this.iptRef.value = '';//清除input的值 解决无法重复上传同样图片问题
            if( this.state.imgIdx !== -1 ){     //判断是否是替换图片
                let list = this.state.imgList;
                list.splice(this.state.imgIdx,1, {
                    id:this.state.imgList[this.state.imgIdx].id,
                    url:e.currentTarget.result
                })
                this.setState({
                    imgList:[...list],
                    imgIdx:-1
                })
            }else{
                this.setState({
                    imgList:[{
                        id: Math.random(),
                        url:e.currentTarget.result
                    },...this.state.imgList]
                })
            }
        }
    }
    render() {
        return(
            <div>
                {
                    this.state.imgList.map((item,index)=>{
                        return (
                                <Img handleUpImg={this.handleUpImg} idx={index} url={item.url} key={item.id} />
                        )
                    })
                }
                <UpInput parent={this} onChangeImgae={this.onChangeUpImage} onRef={(ref)=>this.handleUpImg(ref)} />
            </div>
        )
    }
}